<template>
  <div style="height: 100%">
    <a-tabs v-model:activeKey="activeKey" size="large" class="tab-list">
      <a-tab-pane key="1" :tab="t('查询配置')">
        <div style="padding-top: 10px">
          <p class="tab-title">{{ t('查询配置列表') }}</p>
          <a-table
            size="middle"
            :columns="queryColumns"
            :pagination="false"
            :data-source="generatorConfig.listConfig?.queryConfigs"
            :key="queryTableKey"
            class="search-config"
          >
            <template #headerCell="{ column }">
              <template v-if="column.key === 'sort'">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-fangxiang1" />
                </svg>
              </template>
            </template>
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key !== 'action'">
                <template v-if="column.key === 'sort'">
                  <svg
                    class="icon queryDraggable-icon"
                    aria-hidden="true"
                    :class="isDisabled ? ' cursor-not-allowed' : 'cursor-move'"
                  >
                    <use xlink:href="#icon-paixu" />
                  </svg>
                </template>
                <template v-if="column.key === 'fieldName'">
                  <a-select
                    v-model:value="record[column.dataIndex]"
                    style="width: 100%"
                    :options="querySelectOption"
                    :placeholder="t('请选择查询项')"
                    :disabled="isDisabled"
                  />
                </template>
              </template>
              <template v-if="column.key === 'action'">
                <DeleteTwoTone
                  two-tone-color="#ff8080"
                  @click="queryRemove(index)"
                  :class="isDisabled ? '!cursor-not-allowed' : ''"
                />
              </template>
            </template>
          </a-table>

          <a-button type="dashed" block @click="queryAdd" :disabled="isDisabled">
            <PlusOutlined />
            {{ t('新增') }}
          </a-button>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" :tab="t('列表配置')">
        <div class="tree-left-contain">
          <CollapseContainer class="tree-left-title" :title="t('左侧树配置')">
            <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-form-item :label="t('配置树')">
                <a-switch
                  :disabled="isDisabled"
                  v-model:checked="generatorConfig!.listConfig!.isLeftMenu"
                  @change="changeLeftMenu"
                />
              </a-form-item>
            </a-form>
            <div v-if="generatorConfig?.listConfig?.isLeftMenu" class="tree-left-container">
              <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-form-item :label="t('数据来源')">
                  <a-radio-group
                    :disabled="isDisabled"
                    class="!flex"
                    v-model:value="generatorConfig.listConfig.leftMenuConfig!.datasourceType"
                    button-style="solid"
                    size="default"
                    @change="handleRadioChange"
                  >
                    <a-radio-button value="static">{{ t('静态数据') }}</a-radio-button>
                    <a-radio-button value="api">API</a-radio-button>
                    <a-radio-button value="dic">{{ t('数据字典') }}</a-radio-button>
                  </a-radio-group>
                </a-form-item>
                <div
                  v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'static'"
                  class="static-box"
                >
                  <div
                    v-if="!generatorConfig.listConfig.leftMenuConfig!.staticData?.length"
                    class="static-empty"
                  >
                    {{ t('暂无数据') }}
                  </div>
                  <a-tree
                    v-else
                    block-node
                    showIcon
                    :tree-data="generatorConfig.listConfig.leftMenuConfig!.staticData"
                  >
                    <template #title="item">
                      <div class="tree-node">
                        <span>{{ item.title }}</span>
                        <span :class="isDisabled ? ' cursor-not-allowed' : ''">
                          <Icon
                            icon="ant-design:plus-outlined"
                            @click="addTreeNode(item.key, item.title)"
                            size="14"
                            color="#999"
                          />
                          &nbsp;
                          <Icon
                            icon="ant-design:delete-outlined"
                            size="14"
                            color="#999"
                            @click="
                              delTreeNode(
                                generatorConfig.listConfig.leftMenuConfig!.staticData,
                                item.key,
                              )
                            "
                          />
                        </span>
                      </div>
                    </template>
                  </a-tree>
                  <div @click="addTreeNodeParent" class="add-box">
                    <Icon icon="ant-design:plus-circle-outlined" />
                    {{ t('添加父级') }}
                  </div>
                </div>
                <div v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'dic'">
                  <a-form-item :label="t('数据选项')" required>
                    <DicItemSelect
                      :disabled="isDisabled"
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.dictionaryItemId"
                    />
                  </a-form-item>
                </div>
                <div v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'api'">
                  <a-form-item :label="t('接口配置')" required>
                    <a-input
                      :disabled="isDisabled"
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.apiConfig!.path"
                      :placeholder="t('点击进行接口配置')"
                      @click="showApiDialog"
                    >
                      <template #suffix>
                        <Icon icon="ant-design:ellipsis-outlined" />
                      </template>
                    </a-input>
                  </a-form-item>
                </div>
                <a-form-item :label="t('关联字段')" required>
                  <a-select
                    :disabled="isDisabled"
                    v-model:value="generatorConfig.listConfig.leftMenuConfig!.listFieldName"
                    style="width: 100%"
                    :options="selectOption"
                  />
                </a-form-item>
                <a-form-item :label="t('树形标题')">
                  <a-input
                    :disabled="isDisabled"
                    v-model:value="generatorConfig.listConfig.leftMenuConfig!.menuName"
                    :placeholder="t('请输入树形标题')"
                  />
                </a-form-item>
                <!-- <div v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'dic'">
                  <a-form-item :label="t('图标')">
                    <IconPicker
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.childIcon"
                      :disabled="false"
                      :readonly="false"
                    />
                  </a-form-item>
                </div>
                <div v-else>
                  <a-form-item :label="t('父级图标')">
                    <IconPicker
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.parentIcon"
                      :disabled="false"
                      :readonly="false"
                    />
                  </a-form-item>
                  <a-form-item :label="t('子级图标')">
                    <IconPicker
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.childIcon"
                      :disabled="false"
                      :readonly="false"
                    />
                  </a-form-item>
                </div> -->
              </a-form>
            </div>
          </CollapseContainer>
        </div>
        <div class="right-contarin">
          <div class="right-bottom">
            <CollapseContainer :title="t('列表配置')">
              <div class="right-top">
                <!-- <div class="right-top-list">
                  <span>{{ t('列表标题：') }}</span>
                  <a-input
                    v-model:value="generatorConfig!.listConfig!.listTitle"
                    :placeholder="t('可填写列表标题，非必填')"
                    style="width: 250px"
                  />
                </div> -->
                <div class="right-top-list">
                  {{ t('默认排序') }}
                  <a-switch
                    :disabled="isDisabled"
                    v-model:checked="generatorConfig!.listConfig!.defaultOrder"
                    @change="handleOrderChange"
                  />
                </div>
                <div class="right-top-list">
                  <span class="right-top-file">{{ t('排序字段：') }}</span>
                  <a-select
                    v-model:value="generatorConfig!.listConfig!.orderBy"
                    :options="selectOption"
                    :placeholder="t('请选择排序字段')"
                    :disabled="isDisabled||generatorConfig!.listConfig!.defaultOrder"
                  />
                </div>
                <div class="right-top-list">
                  <span class="right-top-file">{{ t('排序方式：') }}</span>
                  <a-select
                    v-model:value="generatorConfig!.listConfig!.orderType"
                    :disabled="isDisabled"
                  >
                    <a-select-option value="asc">{{ t('升序') }}</a-select-option>
                    <a-select-option value="desc">{{ t('降序') }}</a-select-option>
                  </a-select>
                </div>
              </div>
              <div>
                <a-table
                  size="middle"
                  :columns="listColumns"
                  :pagination="false"
                  :data-source="generatorConfig?.listConfig?.columnConfigs"
                  :key="columnTableKey"
                  class="list-config"
                >
                  <template #headerCell="{ column }">
                    <template v-if="column.key === 'sort'">
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-fangxiang1" />
                      </svg>
                    </template>
                  </template>
                  <template #bodyCell="{ column, record, index }">
                    <template v-if="column.key !== 'action'">
                      <template v-if="column.key === 'sort'">
                        <svg
                          class="icon columnDraggable-icon"
                          :class="isDisabled ? ' cursor-not-allowed' : 'cursor: move'"
                          aria-hidden="true"
                        >
                          <use xlink:href="#icon-paixu" />
                        </svg>
                      </template>
                      <!---如果是checked一类的组件-->
                      <template v-if="column.key === 'columnName'">
                        <a-select
                          v-model:value="record[column.dataIndex]"
                          style="width: 100%"
                          :options="selectOption"
                          @change="(_, option) => handleColumnNameChange(option, index)"
                        />
                      </template>

                      <template v-if="column.key === 'mainField'">
                        <Switch
                          v-model:checked="record[column.dataIndex]"
                          @change="changeMainField(index)"
                        />
                      </template>

                      <template v-if="column.key === 'showLabel'">
                        <Switch v-model:checked="record[column.dataIndex]" />
                      </template>
                    </template>
                    <template v-if="column.key === 'action'">
                      <DeleteTwoTone two-tone-color="#ff8080" @click="columnRemove(index)" />
                    </template>
                  </template>
                </a-table>
                <a-button type="dashed" block @click="columnAdd">
                  <PlusOutlined />
                  {{ t('新增') }}
                </a-button>
              </div>
            </CollapseContainer>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane class="tab-list3" key="3" :tab="t('按钮设置')">
        <div style="padding-top: 10px">
          <p class="tab-title">{{ t('按钮列表') }}</p>
          <a-table
            size="middle"
            :columns="buttonColumns"
            :pagination="false"
            :data-source="generatorConfig?.listConfig?.buttonConfigs"
          >
            <template #bodyCell="{ column, record, index }">
              <!---如果是checked一类的组件-->
              <template v-if="column.key === 'isUse'">
                <a-checkbox v-model:checked="record[column.dataIndex]" />
              </template>
              <template v-if="column.key === 'name'">
                <a-input
                  :disabled="generatorConfig?.listConfig?.buttonConfigs[index].isDefault"
                  v-model:value="record[column.dataIndex]"
                />
              </template>

              <template v-if="column.key === 'code'">
                <a-input
                  :disabled="generatorConfig?.listConfig?.buttonConfigs[index].isDefault"
                  v-model:value="record[column.dataIndex]"
                />
              </template>

              <template v-if="column.key === 'icon'">
                <template v-if="!record.isDefault">
                  <IconPicker v-model:value="record[column.dataIndex]" :disabled="false" />
                </template>
                <template v-else>
                  <a-input v-model:value="record[column.dataIndex]" disabled />
                </template>
              </template>
              <template v-if="column.key === 'action' && !record.isDefault">
                <DeleteTwoTone two-tone-color="#ff8080" @click="buttonRemove(index)" />
              </template>
            </template>
          </a-table>
          <a-button type="dashed" block @click="buttonAdd" v-if="!isCustomForm">
            <PlusOutlined />
            {{ t('新增') }}
          </a-button>
        </div>
      </a-tab-pane>
    </a-tabs>
    <ApiConfig
      v-if="apiConfigDialog"
      :isLeftMenu="true"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="apiConfig"
      :title="t('API配置')"
    />
    <a-modal
      v-model:visible="staticDataVisible"
      :title="modelTitle"
      @ok="addStaticDataParent"
      :afterClose="closeModal"
    >
      <a-form ref="formRef" :model="staticDataParent" style="padding: 20px 20px 0">
        <a-form-item
          :label="t('选项名')"
          name="name"
          :rules="[{ required: true, message: t('请输入选项名') }]"
        >
          <a-input v-model:value="staticDataParent.name" :placeholder="t('请输入选项名')" />
        </a-form-item>
        <a-form-item
          :label="t('选项值')"
          name="value"
          :rules="[{ required: true, message: t('请输入选项值') }]"
        >
          <a-input v-model:value="staticDataParent.value" :placeholder="t('请输入选项值')" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { computed, inject, onMounted, Ref, ref, watch, reactive, unref, nextTick } from 'vue';
  import { PlusOutlined, DeleteTwoTone } from '@ant-design/icons-vue';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { ButtonConfig, ColumnConfig, QueryConfig } from '/@/model/generator/listConfig';
  import { TableFieldConfig } from '/@/model/generator/tableStructureConfig';
  import { ComponentOptionModel } from '/@/model/generator/codeGenerator';
  import { CollapseContainer } from '/@/components/Container/index';
  import { unionWith, cloneDeep } from 'lodash-es';
  import { Switch } from 'ant-design-vue';
  import { DicItemSelect } from '/@/components/DicItemSelect';
  import { IconPicker, Icon } from '/@/components/Icon';
  import { ApiConfig } from '/@/components/ApiConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isNullAndUnDef } from '/@/utils/is';
  import { noShowList, TableInfo, ColumnType } from '/@/components/Designer';
  import Sortable from 'sortablejs';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const props = defineProps({
    //是否是编辑状态
    isUpdate: {
      type: Boolean,
      default: false,
    },
  });
  const { notification } = useMessage();
  const generatorConfig = inject<GeneratorConfig>('generatorConfig') as GeneratorConfig;
  const current = inject<Ref<number>>('current') as Ref<number>;
  const designType = inject<string>('designType', '');
  const tableInfo = inject<Ref<TableInfo[]>>('tableInfo', ref([]));
  const isCustomForm = inject<boolean>('isCustomForm', false);
  const queryColumns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
      width: '5%',
    },
    {
      title: t('查询项'),
      dataIndex: 'fieldName',
      key: 'fieldName',
      width: '50%',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
    },
  ]);

  const listColumns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
      width: '50px',
      align: 'center',
    },
    {
      title: t('列表字段'),
      dataIndex: 'columnName',
      key: 'columnName',
      width: '35%',
    },

    {
      title: t('主字段'),
      dataIndex: 'mainField',
      width: '10%',
      key: 'mainField',
      align: 'center',
    },

    {
      title: t('是否显示标签'),
      dataIndex: 'showLabel',
      width: '15%',
      key: 'showLabel',
      align: 'center',
    },

    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: '80px',
    },
  ]);

  const buttonColumns = ref([
    {
      title: t('启用'),
      dataIndex: 'isUse',
      key: 'isUse',
      width: '5%',
      align: 'center',
    },
    {
      title: t('按钮名称'),
      dataIndex: 'name',
      key: 'name',
      width: '30%',
    },
    {
      title: t('按钮编码'),
      dataIndex: 'code',
      key: 'code',
      width: '30%',
    },
    {
      title: t('按钮图标'),
      dataIndex: 'icon',
      key: 'icon',
      width: '20%',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
    },
  ]);

  const activeKey = ref<string>('1');
  const queryTableKey = ref<number>(0);
  const columnTableKey = ref<number>(0);

  const apiConfigDialog = ref<boolean>(false);

  const staticDataVisible = ref<boolean>(false);

  const staticDataParent = reactive({
    name: '' as string,
    value: '' as string,
  });

  const currentKey = ref('');
  const formRef = ref();
  const modelTitle = ref('');

  const apiConfig = ref({});

  const isDisabled = computed(() => {
    return generatorConfig.outputConfig.funcType === 1 ? false : true;
  });

  onMounted(() => {
    //如果已经有按钮设置了 就不再添加默认值
    if (
      generatorConfig?.listConfig?.buttonConfigs &&
      generatorConfig.listConfig.buttonConfigs.length === 0
    ) {
      generatorConfig.listConfig.buttonConfigs = [
        {
          isUse: true,
          name: t('刷新'),
          code: 'refresh',
          icon: 'ant-design:reload-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('查看'),
          code: 'view',
          icon: 'ant-design:eye-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('新增'),
          code: 'add',
          icon: 'ant-design:plus-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('编辑'),
          code: 'edit',
          icon: 'ant-design:form-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('删除'),
          code: 'delete',
          icon: 'ant-design:delete-outlined',
          isDefault: true,
        },
        {
          isUse: false,
          name: t('发起审批'),
          code: 'startwork',
          icon: 'ant-design:form-outlined',
          isDefault: true,
        },
      ];
    }
  });

  //过滤出 所有主表数据字段  子表的不需要  不在列表页展示的不需要
  const filterMainComponent = (
    list: ComponentOptionModel[] | null,
    isSearch = false,
  ): Recordable[] => {
    if (!list) return [];
    let mainComponents = [] as Recordable[];
    let mainTableFieldConfigs = [] as TableFieldConfig[];

    const remoteComponents = [
      'select',
      'associate-select',
      'associate-popup',
      'multiple-popup',
      'checkbox',
      'radio',
    ];
    generatorConfig.tableStructureConfigs?.forEach((x) => {
      if (x.isMain) mainTableFieldConfigs = x.tableFieldConfigs;
    });
    for (const item of list) {
      //去除子表单组件  和 不在列表页展示的组件
      if (noShowList.includes(item.type)) {
        if (['tab', 'grid', 'card'].includes(item.type)) {
          for (const child of item.layout!) {
            mainComponents = unionWith(mainComponents, filterMainComponent(child.list, isSearch));
          }
        }
      } else if (item.type.indexOf('range') !== -1) {
        //查询配置不要时间范围和日期范围
        if (!isSearch) {
          mainComponents.push({
            key: item.key,
            value: item.bindStartTime,
            label: t(`{name}开始时间`, { name: item.label }),
            type: item.type,
            format: item.options?.format,
          });
          mainComponents.push({
            key: item.key,
            value: item.bindEndTime,
            label: t(`{name}结束时间`, { name: item.label }),
            type: item.type,
            format: item.options?.format,
          });
        }
      } else {
        let notInQuery = false;
        //组件的数据是使用api并且引用组件值作为参数的组件 不进入查询列表
        if (
          ((remoteComponents.includes(item.type) && item.options?.datasourceType === 'api') ||
            item.type === 'cascader') &&
          isSearch
        ) {
          notInQuery = item.options?.apiConfig?.apiParams?.some((para) => {
            const hasFormData = para.tableInfo?.some((info) => {
              if (!info.value) return false;
              return info.bindType === 'data' && info.value?.slice(0, 2) !== '3-';
            });
            return hasFormData;
          });
        }

        if (!notInQuery) {
          if (item.type === 'time' || item.type === 'date') {
            //查询时 时间选择和日期选择需要保存format
            mainComponents.push({
              value: item.bindField,
              label: item.label,
              type: item.type,
              format: item.options?.format,
            });
          } else if (isSearch && item.type === 'info' && item.options?.infoType === 2) {
            //查询时 信息体为当前时间 则查询为时间范围
            mainComponents.push({
              value: item.bindField,
              label: item.label,
              type: item.type,
              // format: 'YYYY-MM-DD HH:mm:ss',
              isDate: true,
            });
          } else {
            let isNumber;

            if (unref(designType) !== 'data') {
              let fieldType;
              mainTableFieldConfigs?.map((x) => {
                if (x.fieldName === item.bindField) {
                  fieldType = x.fieldType;
                }
              });
              isNumber = [2, 3, 7].includes(fieldType);
            } else {
              const table = tableInfo?.value.find((x) => x.isMain); //找到主表信息
              const field = table?.fields.find((x) => x.name === item.bindField); //找到当前字段信息
              isNumber = field?.type === ColumnType.NUMBER;
            }
            mainComponents.push({
              key: item.key,
              value: item.bindField,
              label: item.label,
              type: item.type,
              isNumber,
              componentProps: item.options,
            });
          }
        }
      }
    }

    return mainComponents;
  };
  const getConfigInfo = () => {
    let listComponent = filterMainComponent(generatorConfig!.formJson!.list);
    let queryComponent: any = [];
    if (!isDisabled.value) {
      queryComponent = filterMainComponent(generatorConfig!.formJson!.list, true);
    }
    let queryConfigs: QueryConfig[] = [];
    let columnConfigs: ColumnConfig[] = [];

    // 编辑时 列表配置需要判断key和绑定字段都相同时 则不进行处理
    // key不同并且绑定字段相同（数据优先换了组件但绑定的字段是绑定过的）、key相同绑定字段不同（数据优先已存在的组件换绑字段）
    if (props.isUpdate) {
      //新增时列表配置的组件
      const addColumns = generatorConfig.listConfig.columnConfigs.map((x) => {
        return { key: x.key, field: x.columnName };
      });
      //编辑时列表配置的组件
      const editColumns = listComponent.map((x) => {
        return { key: x.key, field: x.value };
      });
      //编辑时列表配置没有被删除的组件（已经删除的组件删掉）
      columnConfigs = generatorConfig.listConfig.columnConfigs.filter((x) =>
        editColumns.some((clm) => clm.key === x.key && clm.field === x.columnName),
      );
      //除去列表配置新增时已经设置好的组件
      listComponent = listComponent.filter(
        (x) => !addColumns.some((clm) => clm.key === x.key && clm.field === x.value),
      );
      if (!isDisabled.value) {
        //新增时查询配置的组件名称
        const addQueryNames = generatorConfig.listConfig.queryConfigs.map((x) => x.fieldName);
        //编辑时查询配置的组件名称
        const editQueryNames = queryComponent.map((x) => x.value);
        //编辑时查询配置没有被删除的组件（已经删除的组件删掉）
        queryConfigs = generatorConfig.listConfig.queryConfigs.filter((x) =>
          editQueryNames.includes(x.fieldName),
        );
        // //除去查询配置新增时已经设置好的组件
        queryComponent = queryComponent.filter((x) => !addQueryNames.includes(x.value));
      }
    }
    columnConfigs.forEach((component) => {
      if (component.showLabel === undefined) component.showLabel = true;
    });

    generatorConfig.listConfig.columnConfigs = listComponent.map((component) => {
      const columnConfig: ColumnConfig = {
        key: component.key, //数据优先存在编辑时 绑定字段相同的情况 所以需要唯一标识
        columnName: component.value,
        label: component.label,
        columnWidth: '100%',
        mainField: false,
        showLabel: true,
        isNumber: component.isNumber,
        componentType: component.type,
        format: component.format || undefined,
        componentProps: component.componentProps,
      };
      return columnConfig;
    });
    if (!isDisabled.value) {
      generatorConfig.listConfig.queryConfigs = queryComponent.map((component) => {
        const queryConfig: QueryConfig = {
          fieldName: component.value,
          width: 8,
          isDate: ['time', 'date'].includes(component.type) || !!component.isDate,
          format: component.format || undefined,
        };
        return queryConfig;
      });
    }
    if (props.isUpdate) {
      generatorConfig.listConfig.columnConfigs.unshift(...columnConfigs);
      if (!isDisabled.value) generatorConfig.listConfig.queryConfigs.unshift(...queryConfigs);
    }
  };

  watch(
    () => current.value,
    (val) => {
      if (val === 2) {
        getConfigInfo();
        apiConfig.value = cloneDeep(generatorConfig?.listConfig.leftMenuConfig?.apiConfig);
      }
    },
    {
      immediate: true,
    },
  );

  watch(
    () => generatorConfig?.listConfig?.queryConfigs,
    (val) => {
      if (val && val.length) {
        nextTick(() => {
          const tbody: any = document.querySelector('.search-config .ant-table-tbody');
          Sortable.create(tbody, {
            handle: '.queryDraggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isDisabled.value) return;
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(generatorConfig?.listConfig?.queryConfigs);
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex]);
                columns.splice(oldIndex + 1, 1);
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex]);
                columns.splice(oldIndex, 1);
              }
              generatorConfig!.listConfig!.queryConfigs = cloneDeep(columns);
              queryTableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  watch(
    () => [generatorConfig?.listConfig?.columnConfigs, activeKey.value],
    (val) => {
      if (val[0] && val[0].length && val[1] === '2') {
        nextTick(() => {
          const tbody: any = document.querySelector('.list-config .ant-table-tbody');
          Sortable.create(tbody, {
            handle: '.columnDraggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isDisabled.value) return;
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(generatorConfig?.listConfig?.columnConfigs);
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex]);
                columns.splice(oldIndex + 1, 1);
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex]);
                columns.splice(oldIndex, 1);
              }
              generatorConfig!.listConfig!.columnConfigs = cloneDeep(columns);
              columnTableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  watch(
    apiConfig,
    (val) => {
      generatorConfig!.listConfig.leftMenuConfig!.apiConfig = cloneDeep(val);
      delete generatorConfig!.listConfig.leftMenuConfig!.apiConfig?.script;
    },
    {
      deep: true,
    },
  );

  const showApiDialog = () => {
    apiConfigDialog.value = true;
  };

  const changeLeftMenu = (value) => {
    if (value && !generatorConfig?.listConfig?.leftMenuConfig?.datasourceType) {
      generatorConfig!.listConfig!.leftMenuConfig!.datasourceType = 'static';
    }
  };

  const queryAdd = () => {
    if (isDisabled.value) return;
    //给各个组件赋默认值
    const pushObj: QueryConfig = {
      fieldName: '',
      width: 8,
      isDate: false,
    };
    generatorConfig?.listConfig?.queryConfigs.push(pushObj);
  };

  const queryRemove = (index) => {
    if (isDisabled.value) return;
    generatorConfig?.listConfig?.queryConfigs.splice(index, 1);
  };

  const columnAdd = () => {
    //给各个组件赋默认值
    const pushObj: ColumnConfig = {
      key: '',
      label: '',
      columnName: '',
      columnWidth: '100%',
      mainField: false,
      showLabel: true,
      componentType: '',
    };
    generatorConfig?.listConfig?.columnConfigs.push(pushObj);
    // queryOptionData.value.push(pushObj);
  };

  const columnRemove = (index) => {
    generatorConfig?.listConfig?.columnConfigs.splice(index, 1);
  };

  const buttonAdd = () => {
    //给各个组件赋默认值
    const pushObj: ButtonConfig = {
      isUse: true,
      name: '',
      code: '',
      icon: '',
      isDefault: false,
    };
    generatorConfig?.listConfig?.buttonConfigs.push(pushObj);
  };

  const buttonRemove = (index) => {
    generatorConfig?.listConfig?.buttonConfigs.splice(index, 1);
  };

  const closeModal = () => {
    formRef.value.resetFields();
  };

  const addStaticDataParent = async () => {
    const valid = await onCheck();
    if (valid) {
      if (currentKey.value) {
        //子级新增
        findTreeNode(generatorConfig.listConfig.leftMenuConfig!.staticData);
      } else {
        //父级新增
        generatorConfig.listConfig.leftMenuConfig!.staticData?.push({
          title: staticDataParent.name,
          key: staticDataParent.value,
        });
      }
      staticDataVisible.value = false;
    }
  };
  const findTreeNode = (node) => {
    node?.some((item) => {
      if (item.key === currentKey.value) {
        if (!item.children) item.children = [];
        item.children.push({
          title: staticDataParent.name,
          key: staticDataParent.value,
        });
        return true;
      } else {
        if (item.children?.length) {
          return findTreeNode(item.children);
        } else {
          return false;
        }
      }
    });
  };

  const delTreeNode = (node, key) => {
    if (isDisabled.value) return;
    node?.some((item, index) => {
      if (item.key === key) {
        node.splice(index, 1);
        return true;
      } else {
        if (item.children?.length) {
          return delTreeNode(item.children, key);
        } else {
          return false;
        }
      }
    });
  };
  const addTreeNodeParent = () => {
    if (isDisabled.value) return;
    staticDataVisible.value = true;
    currentKey.value = '';
    modelTitle.value = t('添加父级选项');
  };
  const addTreeNode = (key, title) => {
    if (isDisabled.value) return;
    staticDataVisible.value = true;
    currentKey.value = key;
    modelTitle.value = t(`添加【{title}】的子选项`, { title });
  };

  const onCheck = async () => {
    try {
      await formRef.value.validateFields();
      return true;
    } catch (errorInfo) {
      return false;
    }
  };

  const handleOrderChange = (val) => {
    if (val) {
      generatorConfig.listConfig.orderBy = '';
      generatorConfig.listConfig.orderType = undefined;
    }
  };

  const selectOption = computed(() => {
    return filterMainComponent(generatorConfig?.formJson?.list);
  });

  const querySelectOption = computed(() => {
    return filterMainComponent(generatorConfig?.formJson?.list, true);
  });

  //切换数据来源的时候 默认清理掉其他数据
  const handleRadioChange = (e): void => {
    if (e.target.value === 'api') {
      generatorConfig!.listConfig!.leftMenuConfig!.dictionaryItemId = '';
    } else {
      generatorConfig!.listConfig!.leftMenuConfig!.fieldName = '';
      generatorConfig!.listConfig!.leftMenuConfig!.relationFieldName = '';
    }
  };

  const handleColumnNameChange = (option, index) => {
    generatorConfig!.listConfig.columnConfigs[index].componentType = option.type;
    generatorConfig!.listConfig.columnConfigs[index].label = option.label;
  };

  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    const { listConfig } = generatorConfig;
    const {
      queryConfigs,
      columnConfigs,
      buttonConfigs,
      isLeftMenu,
      leftMenuConfig,
      orderBy,
      defaultOrder,
    } = listConfig!;
    const fieldNameAll = [] as string[];

    //TODO 验证查询配置
    for (let i = 0; i < queryConfigs.length; i++) {
      fieldNameAll.push(queryConfigs[i].fieldName);
      if (!queryConfigs[i].fieldName) {
        notification.error({
          message: t('提示'),
          description: t(`查询配置第{index}条，未选择列名！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }
    }
    //判断查询配置查询项是否有重复值
    if ([...new Set(fieldNameAll)].length < fieldNameAll.length) {
      notification.error({
        message: t('提示'),
        description: t('查询配置 查询项不能重复'),
      }); //提示消息
      return false;
    }
    //判断是否有左侧菜单
    if (isLeftMenu) {
      if (!leftMenuConfig) {
        notification.error({
          message: t('提示'),
          description: t('如果需要左侧菜单必须完善配置！'),
        }); //提示消息
        return false;
      }

      if (!leftMenuConfig.datasourceType) {
        notification.error({
          message: t('提示'),
          description: t('必须选择数据来源！'),
        }); //提示消息
        return false;
      }

      if (!leftMenuConfig.listFieldName) {
        notification.error({
          message: t('提示'),
          description: t('必须选择列表关联字段！'),
        }); //提示消息
        return false;
      }

      //如果数据来源为数据字典
      if (leftMenuConfig.datasourceType === 'dic') {
        if (!leftMenuConfig.dictionaryItemId) {
          notification.error({
            message: t('提示'),
            description: t('必须选择数据字典项!'),
          }); //提示消息
          return false;
        }
      }
      //如果数据来源为数据源
      else if (leftMenuConfig.datasourceType === 'datasource') {
        if (!leftMenuConfig.datasourceId) {
          notification.error({
            message: t('提示'),
            description: t('必须选择数据源!'),
          }); //提示消息
          return false;
        }
        //左侧菜单标题
        if (!leftMenuConfig.menuName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-标题!'),
          }); //提示消息
          return false;
        }

        //id字段
        if (!leftMenuConfig.fieldName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-id字段!'),
          }); //提示消息
          return false;
        }

        //父级字段
        if (!leftMenuConfig.parentFiledName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-父级字段!'),
          }); //提示消息
          return false;
        }

        //显示字段
        if (!leftMenuConfig.showFieldName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-显示字段!'),
          }); //提示消息
          return false;
        }

        //关联字段
        if (!leftMenuConfig.relationFieldName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-关联字段!'),
          }); //提示消息
          return false;
        }
      }
    }

    if (!columnConfigs || columnConfigs.length === 0) {
      notification.error({
        message: t('提示'),
        description: t('列表字段配置不能为空!'),
      }); //提示消息
      return false;
    }

    const columnNameAll = [] as string[];

    //验证列表配置
    for (let i = 0; i < columnConfigs.length; i++) {
      columnNameAll.push(columnConfigs[i].columnName);
      if (!columnConfigs[i].columnName) {
        notification.error({
          message: t('提示'),
          description: t(`列表配置第{index}条，未选择列名！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }
    }

    //判断列表配置列表字段是否有重复值
    if ([...new Set(columnNameAll)].length < columnNameAll.length) {
      notification.error({
        message: t('提示'),
        description: t('列表配置 列表字段不能重复'),
      }); //提示消息
      return false;
    }

    //判断排序 如果不是默认排序 需要自己配置排序字段
    if (!defaultOrder) {
      if (!orderBy) {
        notification.error({
          message: t('提示'),
          description: t('如果是非默认排序,必须配置排序字段!'),
        }); //提示消息
        return false;
      }
    }

    //验证按钮配置
    for (let i = 0; i < buttonConfigs.length; i++) {
      if (!buttonConfigs[i].name) {
        notification.error({
          message: t('提示'),
          description: t(`按钮配置第{index}条，未填写按钮名！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }

      if (!buttonConfigs[i].code) {
        notification.error({
          message: t('提示'),
          description: t(`按钮配置第{index}条，未填写按钮编码！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }
    }
    return true;
  };
  function changeMainField(index) {
    generatorConfig?.listConfig?.columnConfigs.forEach((o, idx) => {
      if (idx != index) {
        o.mainField = false;
      }
    });
  }
  defineExpose({ validateStep });
</script>
<style lang="less" scoped>
  :deep(.ant-tabs-nav-wrap) {
    width: 100% !important;
    display: block !important;
    border-top: 8px solid #f0f2f5;
    border-bottom: 3px solid #f0f2f5;
  }

  :deep(.ant-tabs-tab) {
    width: 33.33% !important;
    display: block !important;
    text-align: center !important;
  }

  :deep(.ant-tabs-tabpane) {
    padding: 0 8px;
  }

  :deep(.ant-radio-button-wrapper) {
    flex: 1;
    text-align: center;
    padding: 0 4px;
    display: block;
  }

  .tab-list {
    height: 100%;
  }

  .tree-left-contain {
    width: 350px;
    float: left;
    height: calc(100%);
    border-right: 8px solid #f0f2f5;
    overflow-y: auto;
  }

  .right-contarin {
    padding-left: 15px;
    overflow-y: auto;
    height: calc(100%);
  }

  :deep(.ant-tabs-content) {
    height: 100% !important;
    overflow-y: auto;
  }

  .right-top-list {
    display: inline-block;
    padding-right: 15px;
  }

  .right-top-file {
    display: inline-block;
    padding-right: 10px;
  }

  .right-top-list > div {
    width: 150px !important;
    display: inline-block;
  }

  .right-top {
    border-bottom: 1px solid #e5e7eb;
    padding: 15px 0;
  }

  :deep(.vben-basic-title-normal) {
    font-size: 14px;
    line-height: 18px;
    padding-left: 6px;
    border-left: 6px solid #5e95ff;
  }

  .tree-title-one {
    padding: 8px 0 5px;
  }

  .tree-node {
    display: flex;
    justify-content: space-between;
  }

  .static-box {
    margin: 20px 0;

    .static-empty {
      text-align: center;
    }

    .add-box {
      color: #5e95ff;
      margin-top: 10px;
    }
  }

  .tree-left-container {
    margin: 20px 10px 0 0;

    :deep(.ant-form-item) {
      margin-bottom: 10px;
    }
  }

  :deep(.vben-collapse-container__header) {
    border-bottom: 1px solid #e5e7eb;
  }

  :deep(.ant-tabs-nav) {
    margin-bottom: 0;
  }

  .tab-title {
    font-size: 14px;
    line-height: 18px;
    padding-left: 6px;
    border-left: 6px solid #5e95ff;
  }

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
  }
</style>
